package com.ksr.logistics.shiro;

import com.ksr.logistics.pojo.User;
import com.ksr.logistics.service.PermissionService;
import com.ksr.logistics.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private PermissionService permissionService;

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        String username = (String) authenticationToken.getPrincipal();
        System.out.println("认证:"+username);
        if (username!=null){
            List<User> users=userService.selByUsername(username);
            if (users.size()>0){
                User user=users.get(0);
                String hashedCredentials=user.getPassword();
                String salt=user.getSalt();
                ByteSource credentialsSalt=ByteSource.Util.bytes(salt);
                SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, hashedCredentials, credentialsSalt, getName());
                return info;
            }
        }
        return null;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        User user = (User) principalCollection.getPrimaryPrincipal();
        System.out.println("授权:"+user.getUsername());
        String permissionsInfo=user.getPermissionIds();
        if (StringUtils.isNotBlank(permissionsInfo)){
            String[] idArray=permissionsInfo.split(",");
            List<Long> pids=new ArrayList<>();
            for (int i = 0; i < idArray.length; i++) {
                if (StringUtils.isNumeric(idArray[i])){
                    pids.add(Long.parseLong(idArray[i]));
                }
            }
            List<String> expressions=permissionService.selByPermissionIds(pids);
            SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
            authorizationInfo.addStringPermissions(expressions);

            return authorizationInfo;
        }

        return null;
    }
}
